package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.UserOpLog;
import com.tbit.common.enums.OperaPswEnum;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.business.UserInfo;
import com.tbit.uqbike.object.pojo.UserMember;
import com.tbit.uqbike.object.pojo.VipCard;
import com.tbit.uqbike.object.pojo.dto.PackageDelayDTO;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.OperaPswService;
import com.tbit.uqbike.service.business.VipCardService;
import com.tbit.uqbike.webmanager.business.user_op_log.service.UserOpLogService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 会员卡
 *
 * @Author: chen
 * @Description: 会员卡
 * @Date: 创建于 11:37 2020/7/6
 */
@RestController
@RequestMapping("/vipCard")
public class VipCardController {
    @Autowired
    private VipCardService vipCardService;
    @Autowired
    private UserOpLogService userOpLogService;
    @Autowired
    private OperaPswService operaPswService;

    @RequestMapping("/queryPage")
    public JsonResult queryPage(Integer accountId, @RequestParam(defaultValue = "1") Integer pageNO, @RequestParam(defaultValue = "10") Integer rowCount) {
        Assert.notNull(accountId, "ver.adAccountId.notNull");
        List<VipCard> vipCards = vipCardService.queryPage(accountId, pageNO, rowCount);
        Integer total = vipCardService.queryCount(accountId);
        return JsonResult.ok(vipCards, total);
    }

    /**
     * 添加
     */
    @RequestMapping("/add")
    @OperateLog(module = ModuleEnum.VIPCARD, methods = MethodEnum.VIPCARD_ADD)
    public JsonResult add(VipCard vipCard) {
        Assert.notNull(vipCard.getAccountId(), "ver.adAccountId.notNull");
        Assert.notNull(vipCard.getName(), "ver.vip.name.notNull");
        Assert.notNull(vipCard.getMoney(), "ver.vip.money.notNull");
        Assert.notNull(vipCard.getType(), "ver.vip.type.notNull");
        Assert.notNull(vipCard.getFreeDeposit(), "ver.vip.freeDeposit.notNull");
        if (vipCard.getVipType() == 0 && StringUtils.isNotNull(vipCard.getDiscount()) && vipCard.getDiscount() > 10) {
            throw new BaseException("ver.vip.freeDeposit.too.large");
        }
        if (vipCard.getName().length() > 50){
            throw new BaseException("会员卡名称过长");
        }else if (StrUtil.isNotEmpty(vipCard.getDescription()) && vipCard.getDescription().length() > 200){
            throw new BaseException("会员卡描述过长");
        }else if (StrUtil.isNotEmpty(vipCard.getRemark()) && vipCard.getRemark().length() > 255){
            throw new BaseException("会员卡备注过长");
        }

        vipCardService.add(vipCard);

        // 插入用户操作日志
        UserInfo loginInfo = BaseController.fetchUserInfo();
        userOpLogService.insertSingle(UserOpLog.builder()
                .accountId(vipCard.getAccountId())
                .opUser(loginInfo.getName())
                .opUserPhone(loginInfo.getPhone())
                .operation("会员卡变动")
                .opType("创建")
                .opPlatform(OperationPlatform.MANAGER.code)
                .opTime(LocalDateTime.now())
                .detail("会员卡名称: " + vipCard.getName())
                .result(true)
                .build());

        return JsonResult.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @OperateLog(module = ModuleEnum.VIPCARD, methods = MethodEnum.VIPCARD_EDIT)
    public JsonResult update(VipCard vipCard) {
        Assert.notNull(vipCard.getVipId(), "ver.vip.vipId.notNull");
        if (StrUtil.isNotEmpty(vipCard.getDescription()) && vipCard.getDescription().length() > 200){
            throw new BaseException("会员卡描述过长");
        }else if (StrUtil.isNotEmpty(vipCard.getRemark()) && vipCard.getRemark().length() > 255){
            throw new BaseException("会员卡备注过长");
        }
        vipCardService.update(vipCard);
        return JsonResult.ok();
    }

    /**
     * 逻辑删除
     */
    @RequestMapping("/edit")
    @OperateLog(module = ModuleEnum.VIPCARD, methods = MethodEnum.VIPCARD_CANCAL)
    public JsonResult edit(Integer vipId) {
        Assert.notNull(vipId, "ver.vip.vipId.notNull");
        vipCardService.edit(vipId);
        return JsonResult.ok();
    }

    /**
     * 用户购买记录
     */
    @RequestMapping("/userVipPage")
    public JsonResult userVipPage(Integer accountId, Integer userId, String phone, @RequestParam(defaultValue = "1") Integer pageNO, @RequestParam(defaultValue = "10") Integer rowCount, Date startTime, Date endTime) {
        List<UserMember> list = vipCardService.userVipPage(accountId, userId, phone, pageNO, rowCount, startTime, endTime);
        Integer total = vipCardService.userVipCount(accountId, userId, phone, startTime, endTime);
        return JsonResult.ok(list, total);
    }


    /**
     * 导出会员记录
     * @return fileName
     */
    @PostMapping("/exportUserVip")
    public Result<Object> exportUserVip(Integer accountId, Integer userId, String phone, Date startTime, Date endTime) {
        if (Objects.isNull(startTime) || Objects.isNull(endTime)){
            throw new BaseException("时间参数不能为空");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fileName = String.format("%s~%s 会员记录", sdf.format(startTime), sdf.format(endTime));

        List<UserMember> list = vipCardService.userVipPage(accountId, userId, phone, 1, 65535, startTime, endTime);
        list.forEach(item -> item.setMoneyYuan(NumberUtil.div(item.getMoney().intValue(), 100, 2)));
        ExcelUtil<UserMember> excelUtil = new ExcelUtil<>(UserMember.class);
        JsonResult result = excelUtil.exportExcel(list, fileName);
        return Result.success(result.getData());
    }



    /**
     * 延长会员卡到期时间
     *
     * @param delayDTO .
     * @return .
     */
    @PostMapping("/modifyExpireTime")
    public Result<String> modifyVipCardExpireTime(@RequestBody @Validated PackageDelayDTO delayDTO) {
        delayDTO.valid("会员卡");
        operaPswService.checkOperaPsw(BaseController.getLogin(ServletUtils.getRequest()),
                OperaPswEnum.OPERA_PSW_COUPONS_CONFIG.getModule(), delayDTO.getPwd());
        return vipCardService.modifyVipCardExpireTime(delayDTO);
    }

}
